<template>
  <div class="app-container">

    <el-card>
      <!-- 搜索区域 -->
      <div class="search-card">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input style="width: 100%;" v-model="searchForm.searchName" placeholder="搜索工单号、设备名称" clearable
              @keyup.enter="handleSearch" />
          </el-col>
          <el-col :span="3" style="text-align: left">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 巡检工单列表 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showCreateDialog">新建巡检工单</el-button>
      <!-- 巡检工单表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading" class="mt-2">
        <el-table-column prop="workOrderNumber" label="工单号" align="center" />
        <el-table-column prop="associatedEquipmentName" label="设备名称" align="center" />
        <el-table-column prop="inspectionType" label="巡检类型" align="center">
          <template #default="{ row }">
            <el-tag>
              {{ getName(inspectionTypeOptions, row.inspectionType, 'id', 'name') }}
            </el-tag>

          </template>
        </el-table-column>
        <el-table-column prop="workOrderStatus" label="巡检状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.workOrderStatus)">
              {{ formatStatus(row.workOrderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scheduledInspectionTime" label="计划时间" align="center" />
        <el-table-column prop="executor" label="执行人" align="center">
          <template #default="{ row }">
            <el-tag>
              {{ getName(executorOptions, row.executor, 'id', 'name') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" fixed="right">
          <template #default="{ row }">
            <el-button v-if="row.workOrderStatus === '0'" size="small" type="primary"
              @click="handleStartInspection(row)">开始巡检</el-button>
            <el-button v-else-if="row.workOrderStatus === '1'" size="small" type="success"
              @click="handleFinishInspection(row)">完成巡检</el-button>
            <el-button size="small" @click="showDetailDialog(row)">查看详情</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              v-if="row.workOrderStatus === '0'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 巡检工单详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="'巡检工单详情 - ' + currentInspection.workOrderNumber" width="60%"
      top="5vh">
      <div class="detail-content">
        <h3>基本信息</h3>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="工单号">{{ currentInspection.workOrderNumber }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ currentInspection.associatedEquipmentName }}</el-descriptions-item>
          <el-descriptions-item label="巡检类型">
            <el-tag>
              {{ getName(inspectionTypeOptions, currentInspection.inspectionType, 'id', 'name') }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="计划时间">{{ currentInspection.scheduledInspectionTime }}</el-descriptions-item>
          <el-descriptions-item label="执行人">{{ getName(executorOptions, currentInspection.executor, 'id', 'name')
          }}</el-descriptions-item>
          <el-descriptions-item label="完成时间">{{ currentInspection.completionTime || '--' }}</el-descriptions-item>
          <el-descriptions-item label="工单状态">
            <el-tag :type="getStatusTagType(currentInspection.workOrderStatus)">
              {{ formatStatus(currentInspection.workOrderStatus) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">巡检项目</h3>
        <el-table :data="inspectionItems" border style="width: 100%">
          <el-table-column prop="name" label="项目名称" align="center" />
          <el-table-column prop="standard" label="检查标准" align="center" />
          <el-table-column prop="actual" label="实际值" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === '正常' ? 'success' : row.status === '异常' ? 'danger' : 'info'">
                {{ row.status || '未检查' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="center" />
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 巡检操作对话框 -->
    <el-dialog v-model="operationDialogVisible" :title="'巡检操作 - ' + currentInspection.associatedEquipmentName"
      width="60%" top="5vh">
      <div class="inspection-operation">
        <h3>工单号: {{ currentInspection.workOrderNumber }}</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ currentInspection.associatedEquipmentName }}</el-descriptions-item>
          <el-descriptions-item label="巡检类型">{{ currentInspection.inspectionType }}</el-descriptions-item>
          <el-descriptions-item label="计划时间">{{ currentInspection.scheduledInspectionTime }}</el-descriptions-item>
          <el-descriptions-item label="执行人">{{ currentInspection.executor }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px">巡检项目</h3>
        <div v-for="(item, index) in inspectionItems" :key="index" class="inspection-item">
          <h4>{{ item.name }}</h4>
          <p>检查标准: {{ item.standard }}</p>
          <div>
            <el-radio-group v-model="item.status">
              <el-radio label="正常">正常</el-radio>
              <el-radio label="异常">异常</el-radio>
            </el-radio-group>
            <el-input v-model="item.actual" type="text" placeholder="请输入实际值" style="margin-top: 10px" />
          </div>
        </div>

        <h3 style="margin-top: 20px">备注</h3>
        <el-input v-model="currentInspection.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="operationDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitInspection">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建巡检工单对话框 -->
    <el-dialog v-model="createDialogVisible" title="新建巡检工单" width="50%" @close="resetCreateForm">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="100px">
        <el-form-item label="关联设备" prop="associatedEquipmentId">
          <el-select v-model="createForm.associatedEquipmentId" placeholder="请选择设备" style="width: 100%" filterable>
            <el-option v-for="item in deviceOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检类型" prop="inspectionType">
          <el-select v-model="createForm.inspectionType" placeholder="请选择巡检类型" style="width: 100%">
            <el-option v-for="item in inspectionTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划时间" prop="scheduledInspectionTime">
          <el-date-picker v-model="createForm.scheduledInspectionTime" type="datetime" placeholder="选择计划时间"
            style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="执行人" prop="executor">
          <el-select v-model="createForm.executor" placeholder="请选择执行人" style="width: 100%" filterable>
            <el-option v-for="item in executorOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="巡检项目">
          <div v-for="(item, index) in createForm.inspectionItems" :key="index" class="inspection-item-form">
            <el-row :gutter="20">
              <el-col :span="10">
                <el-input style="width: 100%;" v-model="item.name" placeholder="项目名称" />
              </el-col>
              <el-col :span="10">
                <el-input style="width: 100%;" v-model="item.standard" placeholder="检查标准" />
              </el-col>
              <el-col :span="4">
                <el-button type="danger" @click="removeInspectionItem(index)" circle>
                  <el-icon>
                    <Minus />
                  </el-icon>
                </el-button>
              </el-col>
            </el-row>
          </div>
          <el-button type="primary" style="margin-left: 20px;" @click="addInspectionItem" plain>
            <el-icon>
              <Plus />
            </el-icon>
            添加检查项目
          </el-button>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="createForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createInspection">确认创建</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import {
  getInspectionStatusList,
  getDeviceList,
  getInspectionTypeList,
  getExecutorList,
  getInspectionList,
  getInspectionDetail,
  startInspection,
  finishInspection,
  addInspection,
  deleteInspection,
  getUserListNew
} from '@/api/prod_operate/device/manage/routing'


// 搜索表单
const searchForm = reactive({
  searchName: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页控制
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项数据
const statusOptions = ref([])
const deviceOptions = ref([])
const inspectionTypeOptions = ref([])
const executorOptions = ref([])

// 当前查看的巡检工单
const currentInspection = ref({
  id: '',
  workOrderNumber: '',
  associatedEquipmentName: '',
  scheduledInspectionTime: '',
  inspectionType: '',
  workOrderStatus: '',
  executor: '',
  completionTime: '',
  remark: ''
})

// 巡检项目数据
const inspectionItems = ref([])

// 对话框控制
const detailDialogVisible = ref(false)
const operationDialogVisible = ref(false)
const createDialogVisible = ref(false)

// 新建巡检工单表单
const createForm = reactive({
  associatedEquipmentId: '',
  scheduledInspectionTime: '',
  inspectionType: '',
  executor: '',
  inspectionItems: [
    { name: '', standard: '' }
  ],
  remark: ''
})

const createRules = {
  associatedEquipmentId: [
    { required: true, message: '请选择关联设备', trigger: 'change' }
  ],
  inspectionType: [
    { required: true, message: '请选择巡检类型', trigger: 'change' }
  ],
  scheduledInspectionTime: [
    { required: true, message: '请选择计划时间', trigger: 'change' }
  ],
  executor: [
    { required: true, message: '请选择执行人', trigger: 'change' }
  ]
}

const createFormRef = ref(null)

// 初始化数据
const initData = async () => {
  try {
    // 获取下拉选项数据
    const [
      statusRes,
      deviceRes,
      typeRes,
      executorRes
    ] = await Promise.all([
      getInspectionStatusList(),
      getDeviceList(),
      getInspectionTypeList(),
      getExecutorList()
    ])

    statusOptions.value = statusRes.data
    deviceOptions.value = deviceRes.data
    inspectionTypeOptions.value = typeRes.data
    executorOptions.value = executorRes.data

    // 获取巡检列表数据
    await fetchInspectionList()
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 获取巡检列表数据
const fetchInspectionList = async () => {
  try {
    loading.value = true

    const params = {
      searchName: searchForm.searchName,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    console.log(params);

    const res = await getInspectionList(params)
    console.log(res);

    tableData.value = res.rows
    pagination.total = res.total
  } catch (error) {
    console.error('获取巡检列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取巡检详情数据
const fetchInspectionDetail = async (id) => {
  try {
    const res = await getInspectionDetail(id)
    currentInspection.value = res.data
    inspectionItems.value = res.data.inspectionItems || []
  } catch (error) {
    console.error('获取巡检详情失败:', error)
    ElMessage.error('获取巡检详情失败')
  }
}

// 格式化状态显示
const formatStatus = (status) => {
  const statusMap = {
    '0': '未执行',
    '1': '执行中',
    '2': '已完成',
    '3': '已取消'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info'
  }
  return typeMap[status] || ''
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchInspectionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.searchName = ''
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchInspectionList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchInspectionList()
}

// 显示详情对话框
const showDetailDialog = async (row) => {
  await fetchInspectionDetail(row.id)
  detailDialogVisible.value = true
}

// 开始巡检
const handleStartInspection = async (row) => {
  try {
    await fetchInspectionDetail(row.id)
    operationDialogVisible.value = true
  } catch (error) {
    console.error('开始巡检失败:', error)
    ElMessage.error('开始巡检失败')
  }
}

// 完成巡检
const handleFinishInspection = (row) => {
  ElMessageBox.confirm('确定要完成此巡检工单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await finishInspection({
        id: row.id,
        workOrderStatus: '2' // 2-已完成
      })
      ElMessage.success('巡检工单已完成')
      fetchInspectionList()
    } catch (error) {
      console.error('完成巡检失败:', error)
      ElMessage.error('完成巡检失败')
    }
  }).catch(() => {
    // 取消操作
  })
}

// 提交巡检结果
const submitInspection = async () => {
  try {
    const data = {
      id: currentInspection.value.id,
      inspectionItems: inspectionItems.value,
      remark: currentInspection.value.remark
    }

    await startInspection(data)
    ElMessage.success('巡检结果已提交')
    operationDialogVisible.value = false
    fetchInspectionList()
  } catch (error) {
    console.error('提交巡检结果失败:', error)
    ElMessage.error('提交巡检结果失败')
  }
}

// 删除巡检工单
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除此巡检工单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteInspection(row.id)
      ElMessage.success('删除成功')
      fetchInspectionList()
    } catch (error) {
      console.error('删除巡检工单失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}


// 显示新建巡检工单对话框
const showCreateDialog = () => {
  createDialogVisible.value = true
}

// 添加检查项目
const addInspectionItem = () => {
  createForm.inspectionItems.push({ name: '', standard: '' })
}

// 移除检查项目
const removeInspectionItem = (index) => {
  if (createForm.inspectionItems.length > 1) {
    createForm.inspectionItems.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一个检查项目')
  }
}

// 创建巡检工单
const createInspection = async () => {
  try {
    await createFormRef.value.validate()

    const data = {
      associatedEquipmentId: createForm.associatedEquipmentId,
      scheduledInspectionTime: createForm.scheduledInspectionTime,
      inspectionType: createForm.inspectionType,
      executor: createForm.executor,
      inspectionItems: createForm.inspectionItems.filter(item => item.name && item.standard),
      remark: createForm.remark
    }

    await addInspection(data)
    ElMessage.success('巡检工单创建成功')
    createDialogVisible.value = false
    fetchInspectionList()
  } catch (error) {
    console.error('创建巡检工单失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 重置新建表单
const resetCreateForm = () => {
  createFormRef.value?.resetFields()
  createForm.inspectionItems = [{ name: '', standard: '' }]
  createForm.remark = ''
}

// 初始化
onMounted(async () => {
  initData()

})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 15px;
}

.detail-content h3 {
  margin-bottom: 15px;
  color: #409eff;
}

.inspection-operation {
  padding: 15px;
}

.inspection-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.inspection-item h4 {
  margin-bottom: 10px;
  color: #606266;
}

.inspection-item p {
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.inspection-item-form {
  margin-bottom: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.search-card :deep(.el-form-item),
.search-card :deep(.el-form) {
  margin-bottom: 0px !important;
}
</style>